package com.xizimall.sso.service.impl;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.aspectj.apache.bcel.generic.ReturnaddressType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.mysql.fabric.xmlrpc.base.Data;
import com.xizimall.mapper.TbUserMapper;
import com.xizimall.pojo.TbUser;
import com.xizimall.pojo.TbUserExample;
import com.xizimall.pojo.TbUserExample.Criteria;
import com.xizimall.sso.dao.JedisClient;
import com.xizimall.sso.service.UserService;
import com.xizimall.common.pojo.XizimallResult;
import com.xizimall.common.utils.CookieUtils;
import com.xizimall.common.utils.JsonUtils;

import redis.clients.jedis.Jedis;
/**
 * 用户校验服务
 * <p>Title: UserServiceImpl</p>
 * <p>Description: </p>
 * <p>华南理工大学研究生</p> 
 * @author	李隆熹
 * @date	2018年4月26日下午4:20:56
 * @version 1.0
 */
@Service
public class UserServiceImpl implements UserService {
    
	@Autowired
	private TbUserMapper userMapper;
	
	@Value("${REDIS_USER_SESSION_KEY}")
	private String REDIS_USER_SESSION_KEY;
	
	@Value("${SSO_SESSION_EXPIRE}")
	private Integer SSO_SESSION_EXPIRE;
	
	@Value("${PORTAL_BASE_URL}")
	private String PORTAL_BASE_URL;
	
	@Autowired
	private JedisClient jedisClient;
	
	@Override
	public XizimallResult checkData(String context, Integer type) {
		//创建查询条件
		TbUserExample example=new TbUserExample();
		Criteria criteria=example.createCriteria();
		//type1,2,3分别代表username,phone,email
		//校验用户名
		if(1==type){
			criteria.andUsernameEqualTo(context);
		}//校验电话
		else if(2==type){
			criteria.andPhoneEqualTo(context);
		}//校验邮箱
		else{
			criteria.andEmailEqualTo(context);
		}
		//执行查询
		List<TbUser> list=userMapper.selectByExample(example);
		if(list==null||list.size()==0){
			return XizimallResult.ok(true);
		}
		return XizimallResult.ok(false);
	}

	@Override
	public XizimallResult createUser(TbUser user) {
		user.setCreated(new Date());
		user.setUpdated(new Date());
		//mds加密
		user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
		
		userMapper.insert(user);
		return XizimallResult.ok();
	}
   /**
    * 用户登录
    * <p>Title: userLogin</p>
    * <p>Description: </p>
    * @param username
    * @param password
    * @return
    * @see com.xizimall.sso.service.UserService#userLogin(java.lang.String, java.lang.String)
    */
	@Override
	public XizimallResult userLogin(String username, String password
			,HttpServletRequest request,HttpServletResponse response) {
		TbUserExample example = new TbUserExample();
		Criteria criteria = example.createCriteria();
		criteria.andUsernameEqualTo(username);
		List<TbUser> list = userMapper.selectByExample(example);
		//aa如果没有此用户名
		if(null==list||list.size()==0){
			return XizimallResult.build(400, "用户名或密码错误");
		}
		TbUser user = list.get(0);
		if(!DigestUtils.md5DigestAsHex(password.getBytes()).equals(user.getPassword())){
			return XizimallResult.build(400, "密码错误");
		}
		//生成token
		String token =UUID.randomUUID().toString();
		//保存用户之前把用户对象中的密码清空
		user.setPassword(null);
		//把用户信息写入redis
		jedisClient.set(REDIS_USER_SESSION_KEY+":"+token,JsonUtils.objectToJson(user));
		//设置session的过期时间
		jedisClient.expire(REDIS_USER_SESSION_KEY+":"+token,SSO_SESSION_EXPIRE );
		//添加些cookie的逻辑,有效期是关闭浏览器就失效
		CookieUtils.setCookie(request, response, "TT_TOKEN", token);
		return XizimallResult.ok(token);
	}

@Override
public XizimallResult getUserByToken(String token) {
	//根据token向redis查询用户信息
	String json = jedisClient.get(REDIS_USER_SESSION_KEY+":"+token);
	//判断是否为空
	if(StringUtils.isBlank(json)){
		return XizimallResult.build(400, "次session已过期,请重新登录");
	}
	//更新过期时间
	jedisClient.expire(REDIS_USER_SESSION_KEY+":"+token,SSO_SESSION_EXPIRE);
	//返回用户信息
	return XizimallResult.ok(JsonUtils.jsonToPojo(json, TbUser.class));
}

@Override
public void userLogout(
		HttpServletRequest request, HttpServletResponse response) {
	String token = CookieUtils.getCookieValue(request, "TT_TOKEN");
	jedisClient.del(REDIS_USER_SESSION_KEY+":"+token);
	try {
		response.sendRedirect(PORTAL_BASE_URL);
	} catch (IOException e) {
		
		e.printStackTrace();
	}
}

}
